package com.topscomm.file.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;

import org.apache.tika.metadata.HttpHeaders;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaMetadataKeys;
import org.apache.tika.mime.MediaType;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.xml.sax.helpers.DefaultHandler;

import com.topscomm.core.FileFormatEnum;

/**
 * 文件操作
 * 
 * @description:
 * @author: donghang
 * @date: 2020年8月19日下午6:10:16
 * @modify:
 */
public class FileUtil {
	/**
	 * 文件加密
	 * 
	 * @description:
	 * @param filePath
	 * @throws Exception
	 * @author: donghang
	 * @date: 2020年8月19日下午5:42:23
	 * @modify:
	 */
	public static void encrypt(String filePath) throws Exception {
		File file = new File(filePath);
		if (!file.exists()) {
			throw new FileNotFoundException(filePath + "文件不存在");
		}
		String destFilePath = file.getParent() + "/" + "encrypt-" + file.getName();
		File destfile = new File(destFilePath);
		if (destfile.exists()) {
			destfile.delete();
		}
		// 获取待加密文件的输入流
		InputStream in = new FileInputStream(filePath);
		// 创建中转文件输出流
		OutputStream out = new FileOutputStream(destFilePath);
		// 待加密文件的流
		byte[] oldBuffer = new byte[1024];
		// 加密之后的文件的流
		byte[] encryptBuffer = new byte[1024];
		int readByteCount;
		while ((readByteCount = in.read(oldBuffer)) > 0) {
			for (int i = 0; i < readByteCount; i++) {
				byte b = oldBuffer[i];
				// 每个字节加2加密
				b += 2;
				encryptBuffer[i] = b;

			}
			out.write(encryptBuffer, 0, readByteCount);
			out.flush();
		}
		in.close();
		out.close();
	}

	/**
	 * 解密文件
	 * 
	 * @description:
	 * @param filePath
	 * @param tempFilePath
	 * @param keyLength
	 * @return
	 * @throws Exception
	 * @author: donghang
	 * @date: 2020年8月19日下午5:54:48
	 * @modify:
	 */
	public static String decrypt(String filePath, String tempFilePath, int keyLength) throws Exception {
		File file = new File(filePath);
		if (!file.exists()) {
			throw new FileNotFoundException(filePath + "文件不存在");
		}
		// 创建文件夹
		File dest = new File(tempFilePath);
		if (!dest.getParentFile().exists()) {
			dest.getParentFile().mkdirs();
		}
		// 获取待解密的文件输入流
		InputStream is = new FileInputStream(filePath);
		// 创建目标文件输出流，用来生成解密后的文件
		OutputStream out = new FileOutputStream(tempFilePath);
		byte[] buffer = new byte[1024];
		byte[] decryptBuffer = new byte[1024];
		// 去除尾部加密串
		long size = file.length() - keyLength;
		int mod = (int) (size % 1024);
		int div = (int) (size >> 10);
		int blockCount = mod == 0 ? div : (div + 1);
		int blockNum = 1, readByteCount;
		while ((blockNum <= blockCount && (readByteCount = is.read(buffer)) > 0)) {
			if (mod != 0 && blockNum == blockCount) {
				readByteCount = mod;
			}
			for (int i = 0; i < readByteCount; i++) {
				byte b = buffer[i];
				b -= 2;
				decryptBuffer[i] = b;
			}
			out.write(decryptBuffer, 0, readByteCount);
			blockNum++;
		}
		out.close();
		is.close();
		return tempFilePath;
	}

	/**
	 * 得到文件类型
	 * 
	 * @description:
	 * @param fileName
	 * @return
	 * @author: donghang
	 * @date: 2021年3月16日上午10:47:50
	 * @modify:
	 */
	public static String getMimeType(String filePath) {
		File file = new File(filePath);
		AutoDetectParser parser = new AutoDetectParser();
		parser.setParsers(new HashMap<MediaType, Parser>());
		Metadata metadata = new Metadata();
		metadata.add(TikaMetadataKeys.RESOURCE_NAME_KEY, file.getName());
		try (InputStream stream = new FileInputStream(file)) {
			parser.parse(stream, new DefaultHandler(), metadata, new ParseContext());
		} catch (Exception e) {
			throw new RuntimeException(filePath + "获取mime type失败");
		}
		return metadata.get(HttpHeaders.CONTENT_TYPE);
	}

	/**
	 * @description: 判断mimetype是否匹配
	 * @param mimeType
	 * @param fileMimeType
	 * @return
	 * @author: wanghongwei
	 * @date: 2021-3-18 8:53:11
	 * @modify:
	 */
	public static boolean matchMimeType(String mimeType, String fileMimeType) {
		String[] mimeTypeArr = fileMimeType.split(",");
		boolean isMatch = false;
		for (String type : mimeTypeArr) {
			if (mimeType.contains(type)) {
				isMatch = true;
				break;
			}
		}
		return isMatch;
	}

	/**
	 * office文档类型
	 * 
	 * @description:
	 * @param mimeType
	 * @return
	 * @author: donghang
	 * @date: 2021年4月8日下午2:01:06
	 * @modify:
	 */
	public static boolean matchOfficeMimeType(String mimeType) {
		if (FileUtil.matchMimeType(mimeType, FileFormatEnum.PDF.mimeType)) {
			return true;
		}
		if (FileUtil.matchMimeType(mimeType, FileFormatEnum.WORD.mimeType)) {
			return true;
		}
		if (FileUtil.matchMimeType(mimeType, FileFormatEnum.EXCEL.mimeType)) {
			return true;
		}
		if (FileUtil.matchMimeType(mimeType, FileFormatEnum.PPT.mimeType)) {
			return true;
		}
		return false;
	}

	/**
	 * 匹配视频类型
	 * 
	 * @description:
	 * @param mimeType
	 * @return
	 * @author: donghang
	 * @date: 2021年4月8日下午2:03:59
	 * @modify:
	 */
	public static boolean matchVideoMimeType(String mimeType) {
		if (FileUtil.matchMimeType(mimeType, FileFormatEnum.VIDEO.mimeType)) {
			return true;
		}
		return false;
	}
}
